class Ssp::ReportItem < ApplicationRecord
  belongs_to :report, touch: true

  validates_presence_of :commodity_type, :commodity_id, :price, :count

  COMMODITY_TYPES = {
    '代买': 'buy',
    '代卖': 'sale',
  }

  COMMODITIES = {
    4 => %w(农产品 粮油类),
    5 => %w(农产品 生鲜食品类),
    6 => %w(农产品 干货类),
    8 => %w(工业消费品 休闲食品类),
    9 => %w(工业消费品 烟酒类),
    10 => %w(工业消费品 服装、鞋帽、针纺织品类),
    11 => %w(工业消费品 化妆品类),
    12 => %w(工业消费品 金银珠宝类),
    13 => %w(工业消费品 日用品类),
    14 => %w(工业消费品 家用电器和音像器材类),
    15 => %w(工业消费品 中西药品类),
    16 => %w(工业消费品 文化办公用品类),
    17 => %w(工业消费品 家具类),
    18 => %w(工业消费品 通讯器材类),
    19 => %w(工业消费品 建筑及装潢材料类),
    20 => %w(生产资料 农用生产资料类),
    21 => %w(生产资料 化工产品类),
    22 => %w(生产资料 机电类),
    23 => %w(生产资料 木材类),
  }

  SALE_COMMODITY_MAPPING = {
    4 => 27,
    5 => 28,
    6 => 29,
    8 => 30,
    9 => 32,
    10 => 33,
    11 => 34,
    12 => 35,
    13 => 36,
    14 => 37,
    15 => 38,
    16 => 39,
    17 => 40,
    18 => 41,
    19 => 42,
    20 => 43,
    21 => 44,
    22 => 45,
    23 => 46,
  }

  def commodity
    COMMODITIES[commodity_id]
  end

  def human_commodity
    commodity && commodity.last
  end

  def human_commodity_type
    COMMODITY_TYPES.key commodity_type
  end

  def commodity_id_for_report
    commodity_type == 'buy' ? commodity_id : SALE_COMMODITY_MAPPING[commodity_id]
  end

  def self.grouped_commodites_for_select_options
    select_options = {}
    COMMODITIES.each do |id, commodity|
      group, type = commodity
      select_options[group] ||= []
      select_options[group] << [type, id]
    end
    select_options
  end

end
